import streamlit as st
import os
from typing import List
from pathlib import Path

from ..utils.session_state import set_file_info
from ..core.file_validator import validate_file, get_file_info
from ..core.document_processor import DocumentProcessor

def render_main_page():
    """渲染主页面"""
    
    # 页面标题
    st.markdown('<div class="main-header">📄 数据预处理工具</div>', unsafe_allow_html=True)
    
    # 创建三列布局
    col1, col2, col3 = st.columns([2, 1, 2])
    
    with col1:
        render_file_upload_section()
    
    with col2:
        st.markdown("<div style='text-align: center; padding-top: 2rem;'>→</div>", unsafe_allow_html=True)
    
    with col3:
        render_quick_process_section()
    
    # 处理状态管理
    processing_status = st.session_state.get('processing_status', 'idle')
    
    # 如果状态是processing且还没有开始处理，则开始处理
    if processing_status == 'processing' and not st.session_state.get('processing_started', False):
        st.session_state.processing_started = True
        with st.spinner("⏳ 正在处理文档，请稍候..."):
            start_processing()
    
    # 显示处理状态
    if processing_status == 'processing':
        st.info("⏳ 正在处理文档，请稍候...")
    
    # 处理完成后显示弹窗
    if processing_status == 'completed':
        # 显示处理完成弹窗
        if st.session_state.get('processing_result') and not st.session_state.get('completion_dialog_shown'):
            show_completion_dialog()
            st.session_state.completion_dialog_shown = True
    
    # 文件信息显示
    if st.session_state.get('uploaded_files'):
        render_file_info_section()
    
    # 自定义分隔符导出功能
    if st.session_state.get('processed_documents'):
        render_custom_separator_export()

def render_file_upload_section():
    """渲染文件上传区域"""
    
    st.subheader("📁 文件上传")
    
    # 文件上传组件
    uploaded_files = st.file_uploader(
        "选择文档文件",
        type=['pdf', 'docx', 'md'],
        accept_multiple_files=True,
        help="支持PDF、Word(.docx)、Markdown(.md)格式，最大文件大小200MB",
        key="file_uploader"
    )
    
    if uploaded_files:
        # 验证和处理上传的文件
        valid_files = []
        for file in uploaded_files:
            try:
                # 验证文件
                is_valid, error_msg = validate_file(file)
                if is_valid:
                    valid_files.append(file)
                    # 获取文件信息
                    file_info = get_file_info(file)
                    set_file_info(file.name, file_info)
                    st.success(f"✅ {file.name} - 验证通过")
                else:
                    st.error(f"❌ {file.name} - {error_msg}")
            except Exception as e:
                st.error(f"❌ {file.name} - 处理出错: {str(e)}")
        
        # 更新会话状态
        st.session_state.uploaded_files = valid_files
        
        if valid_files:
            st.info(f"已成功上传 {len(valid_files)} 个文件")
    
    # 清除文件按钮
    if st.session_state.get('uploaded_files'):
        if st.button("🗑️ 清除所有文件", type="secondary"):
            # 清除所有文件相关的状态
            st.session_state.uploaded_files = []
            st.session_state.file_info = {}
            # 清除处理结果
            if 'processed_documents' in st.session_state:
                del st.session_state.processed_documents
            # 重置处理状态
            st.session_state.processing_status = 'idle'
            st.session_state.processing_started = False
            st.session_state.processing_progress = 0
            st.session_state.processing_message = ""
            st.success("已清除所有文件和处理结果")
            st.rerun()

def render_quick_process_section():
    """渲染快速处理面板"""
    
    st.subheader("⚡ 快速处理")
    
    # 预设模板
    templates = {
        "标准清洗 + 固定长度切片": {
            "description": "适合大多数文档，500字符/段，50字符重叠",
            "cleaning": {
                'remove_empty_lines': True,
                'remove_duplicates': True,
                'remove_headers_footers': True,
                'remove_special_chars': True,
                'normalize_text': True,
                'fix_line_breaks': True
            },
            "chunking": {
                'strategy': '固定长度分段',
                'chunk_size': 500,
                'overlap_size': 50
            }
        },
        "保留结构 + 文档层级切片": {
            "description": "保留原文档结构，按章节标题分段",
            "cleaning": {
                'remove_empty_lines': True,
                'remove_duplicates': False,
                'remove_headers_footers': False,
                'remove_special_chars': False,
                'normalize_text': True,
                'fix_line_breaks': True
            },
            "chunking": {
                'strategy': '按文档结构分段',
                'max_depth': 3,
                'preserve_structure': True
            }
        },
        "深度清洗 + 内容类型切片": {
            "description": "彻底清洗，按段落、列表、表格分类",
            "cleaning": {
                'remove_empty_lines': True,
                'remove_duplicates': True,
                'remove_headers_footers': True,
                'remove_special_chars': True,
                'normalize_text': True,
                'fix_line_breaks': True
            },
            "chunking": {
                'strategy': '按内容类型分段',
                'preserve_structure': False
            }
        }
    }
    
    # 显示模板选项
    for template_name, template_config in templates.items():
        with st.container():
            st.markdown(f"**{template_name}**")
            st.caption(template_config["description"])
            
            # 检查是否正在处理
            is_processing = st.session_state.get('processing_status') == 'processing'
            
            if st.button(f"使用此模板", key=f"template_{template_name}", disabled=is_processing):
                # 应用模板配置
                st.session_state.cleaning_config.update(template_config["cleaning"])
                st.session_state.chunking_config.update(template_config["chunking"])
                st.success(f"已应用模板: {template_name}")
                st.info("模板已应用，请点击'开始处理'按钮来处理文件")
                # 不再自动开始处理，让用户手动点击开始处理按钮
            
            st.divider()
    
    # 自定义配置按钮
    if st.button("🔧 自定义配置", type="primary"):
        # 使用query_params来触发页面跳转，避免直接修改session_state
        st.query_params.page = "处理配置"
        st.rerun()



def render_file_info_section():
    """渲染文件信息区域"""
    
    st.subheader("📋 文件信息")
    
    files = st.session_state.get('uploaded_files', [])
    
    if files:
        # 创建文件信息表格
        file_data = []
        for file in files:
            info = st.session_state.file_info.get(file.name, {})
            file_data.append({
                "文件名": file.name,
                "格式": info.get('format', 'Unknown'),
                "大小": f"{info.get('size_mb', 0):.2f} MB",
                "页数/段落": info.get('pages', info.get('paragraphs', 'N/A')),
                "状态": "✅ 就绪"
            })
        
        # 显示表格
        st.table(file_data)
        
        # 开始处理按钮
        processing_status = st.session_state.get('processing_status', 'idle')
        is_processing = processing_status == 'processing'
        
        # 根据处理状态显示不同的按钮文本
        if is_processing:
            button_text = "⏳ 处理中..."
            button_type = "secondary"
        else:
            button_text = "🚀 开始处理"
            button_type = "primary"
        
        col1, col2 = st.columns([3, 1])
        with col1:
            # 使用唯一的key来确保按钮状态正确更新
            if st.button(button_text, type=button_type, use_container_width=True, disabled=is_processing, key="start_processing_btn"):
                # 立即设置处理状态，防止重复点击
                st.session_state.processing_status = 'processing'
                st.session_state.completion_dialog_shown = False  # 重置弹窗状态
                # 立即重新运行以更新按钮状态
                st.rerun()
                # 开始处理将在下次运行时执行
        
        with col2:
            if is_processing and st.button("🔄 重置", help="如果处理卡住，点击重置状态"):
                st.session_state.processing_status = 'idle'
                st.session_state.processing_started = False
                st.success("已重置处理状态")
                st.rerun()



def show_completion_dialog():
    """显示处理完成的提示弹窗"""
    
    # 使用 Streamlit 的弹窗样式
    st.balloons()  # 添加庆祝动画
    
    # 显示简单的成功消息
    st.success("🎉 切片完成！文档已成功处理")
    
    # 简单的操作按钮
    col1, col2 = st.columns(2)
    
    with col1:
        if st.button("👀 查看结果", type="primary", use_container_width=True, key="dialog_view_results"):
            st.query_params.page = "结果预览"
            st.rerun()
    
    with col2:
        if st.button("🔄 继续处理", type="secondary", use_container_width=True, key="dialog_continue_processing"):
            # 重置状态，允许用户继续处理其他文件
            st.session_state.processing_status = 'idle'
            st.session_state.completion_dialog_shown = False
            if 'processing_result' in st.session_state:
                del st.session_state.processing_result
            st.rerun()

def start_processing():
    """开始文档处理"""
    
    if not st.session_state.get('uploaded_files'):
        st.error("请先上传文件")
        st.session_state.processing_status = 'idle'
        return
    
    try:
        import time
        start_time = time.time()
        
        print("[DEBUG] 开始文档处理...")
        
        # 获取当前配置
        from ..ui.config_page import get_current_config
        current_config = get_current_config()
        
        # 确保有chunking_config
        if 'chunking_config' not in st.session_state:
            st.session_state['chunking_config'] = {
                'strategy': '固定长度分段',
                'chunk_size': 1000,
                'overlap_size': 100
            }
        
        # 从完整配置中提取切片配置
        chunking_config = current_config.copy()
        current_strategy = chunking_config.get('strategy', '固定长度分段')
        print(f"[DEBUG] 使用切片策略: {current_strategy}")
        
        # 创建文档处理器
        print("[DEBUG] 创建文档处理器...")
        processor = DocumentProcessor(
            cleaning_config=current_config,
            chunking_config=chunking_config
        )
        
        # 处理文件
        files = st.session_state.uploaded_files
        total_files = len(files)
        print(f"[DEBUG] 准备处理 {total_files} 个文件")
        
        # 清空之前的处理结果
        st.session_state.processed_documents = []
        
        for i, file in enumerate(files):
            try:
                print(f"[DEBUG] 开始处理文件 {i+1}/{total_files}: {file.name}")
                
                # 处理单个文件
                result = processor.process_file(file)
                
                if result:
                    print(f"[DEBUG] 文件 {file.name} 处理成功，生成 {len(result.get('chunks', []))} 个切片")
                    st.session_state.processed_documents.append(result)
                else:
                    print(f"[DEBUG] 文件 {file.name} 处理失败")
                    st.warning(f"文件 {file.name} 处理失败，已跳过")
                    
            except Exception as file_error:
                print(f"[DEBUG] 处理文件 {file.name} 时出错: {str(file_error)}")
                st.warning(f"处理文件 {file.name} 时出错: {str(file_error)}")
                continue
        
        # 检查是否有成功处理的文件
        if not st.session_state.processed_documents:
            st.error("没有文件被成功处理，请检查文件格式或内容")
            st.session_state.processing_status = 'idle'
            st.rerun()
            return
        
        # 处理完成
        total_chunks = sum(len(doc.get('chunks', [])) for doc in st.session_state.processed_documents)
        processing_time = time.time() - start_time
        
        # 设置完成状态和结果信息
        st.session_state.processing_status = 'completed'
        st.session_state.processing_started = False  # 重置处理开始标志
        st.session_state.processing_result = {
            'file_count': total_files,
            'chunk_count': total_chunks,
            'processing_time': processing_time
        }
        
        print("[DEBUG] 处理完成，显示结果摘要")
        
        # 处理完成后重新渲染页面以更新状态
        st.rerun()
        
    except Exception as e:
        print(f"[DEBUG] 处理过程中发生错误: {str(e)}")
        import traceback
        print(f"[DEBUG] 错误堆栈: {traceback.format_exc()}")
        
        # 重置处理状态
        st.session_state.processing_status = 'idle'
        
        st.error(f"处理失败: {str(e)}")
        st.error("请检查终端输出获取详细错误信息")
        
        # 出错后重新渲染页面以更新状态
        st.rerun()

def render_custom_separator_export():
    """渲染自定义分隔符导出功能"""
    
    st.markdown("---")
    st.subheader("🔧 自定义分隔符导出")
    st.markdown("将切片数据导出为使用自定义分隔符的格式")
    
    # 创建两列布局
    col1, col2 = st.columns(2)
    
    with col1:
        st.markdown("**分隔符设置**")
        
        # 父段分隔符设置
        parent_separator = st.text_input(
            "父段分隔符",
            value=st.session_state.get('parent_separator', '@@@'),
            help="用于分隔不同切片的主要分隔符"
        )
        
        # 子段分隔符设置
        child_separator = st.text_input(
            "子段分隔符",
            value=st.session_state.get('child_separator', '###'),
            help="用于切片内部分段的次要分隔符"
        )
        
        # 保存分隔符设置
        st.session_state.parent_separator = parent_separator
        st.session_state.child_separator = child_separator
        
        # 导出选项
        st.markdown("**导出选项**")
        
        include_metadata = st.checkbox(
            "包含元数据信息",
            value=st.session_state.get('include_metadata', False),
            help="在导出文件中包含切片的元数据信息"
        )
        
        export_format = st.selectbox(
            "导出格式",
            options=["txt", "md"],
            format_func=lambda x: {"txt": "纯文本 (.txt)", "md": "Markdown (.md)"}[x],
            help="选择导出文件的格式"
        )
    
    with col2:
        st.markdown("**预览效果**")
        
        # 获取第一个文档的前3个切片作为预览
        if st.session_state.processed_documents:
            first_doc = st.session_state.processed_documents[0]
            chunks = first_doc.get('chunks', [])
            preview_chunks = chunks[:3]  # 只显示前3个切片
            
            preview_content = generate_custom_separator_content(
                preview_chunks, parent_separator, child_separator, include_metadata
            )
            
            st.code(preview_content[:500] + "..." if len(preview_content) > 500 else preview_content, language="text")
            
            if len(chunks) > 3:
                st.caption(f"预览显示前3个切片，实际共有 {len(chunks)} 个切片")
    
    # 导出按钮
    st.markdown("**导出操作**")
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("📄 导出单个文件", use_container_width=True):
            export_single_file_with_separators(parent_separator, child_separator, include_metadata, export_format)
    
    with col2:
        if st.button("📁 导出所有文件", use_container_width=True):
            export_all_files_with_separators(parent_separator, child_separator, include_metadata, export_format)
    
    with col3:
        if st.button("🔄 合并导出", use_container_width=True):
            export_merged_file_with_separators(parent_separator, child_separator, include_metadata, export_format)

def generate_custom_separator_content(chunks, parent_separator, child_separator, include_metadata=False):
    """生成使用自定义分隔符的内容"""
    
    content_parts = []
    
    for i, chunk in enumerate(chunks):
        chunk_content = chunk.get('content', '')
        
        if include_metadata:
            metadata = chunk.get('metadata', {})
            metadata_info = f"切片ID: {chunk.get('chunk_id', f'chunk_{i}')}\n"
            metadata_info += f"字符数: {metadata.get('char_count', len(chunk_content))}\n"
            metadata_info += f"词数: {metadata.get('word_count', len(chunk_content.split()))}\n"
            if metadata.get('strategy_used'):
                metadata_info += f"切片策略: {metadata.get('strategy_used')}\n"
            
            # 使用子段分隔符分隔元数据和内容
            chunk_text = f"{metadata_info}{child_separator}\n{chunk_content}"
        else:
            chunk_text = chunk_content
        
        content_parts.append(chunk_text)
    
    # 使用父段分隔符连接所有切片
    return f"\n{parent_separator}\n".join(content_parts)

def export_single_file_with_separators(parent_separator, child_separator, include_metadata, export_format):
    """导出单个文件（用户选择）"""
    
    if not st.session_state.processed_documents:
        st.error("没有可导出的文档")
        return
    
    # 让用户选择要导出的文档
    doc_names = [doc.get('filename', f'文档{i+1}') for i, doc in enumerate(st.session_state.processed_documents)]
    
    selected_doc = st.selectbox(
        "选择要导出的文档",
        options=range(len(doc_names)),
        format_func=lambda x: doc_names[x],
        key="export_single_doc_selector"
    )
    
    if st.button("确认导出", key="confirm_export_single"):
        doc = st.session_state.processed_documents[selected_doc]
        chunks = doc.get('chunks', [])
        
        content = generate_custom_separator_content(chunks, parent_separator, child_separator, include_metadata)
        
        filename = f"{doc.get('filename', 'document').split('.')[0]}_custom_separators.{export_format}"
        
        st.download_button(
            label=f"📥 下载 {filename}",
            data=content,
            file_name=filename,
            mime="text/plain" if export_format == "txt" else "text/markdown"
        )
        
        st.success(f"已生成导出文件: {filename}")

def export_all_files_with_separators(parent_separator, child_separator, include_metadata, export_format):
    """导出所有文件（分别导出）"""
    
    if not st.session_state.processed_documents:
        st.error("没有可导出的文档")
        return
    
    import zipfile
    import io
    from datetime import datetime
    
    # 创建ZIP文件
    zip_buffer = io.BytesIO()
    
    with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
        for i, doc in enumerate(st.session_state.processed_documents):
            chunks = doc.get('chunks', [])
            content = generate_custom_separator_content(chunks, parent_separator, child_separator, include_metadata)
            
            filename = f"{doc.get('filename', f'document_{i+1}').split('.')[0]}_custom_separators.{export_format}"
            zip_file.writestr(filename, content)
    
    zip_buffer.seek(0)
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    zip_filename = f"custom_separators_export_{timestamp}.zip"
    
    st.download_button(
        label=f"📥 下载所有文件 ({zip_filename})",
        data=zip_buffer.getvalue(),
        file_name=zip_filename,
        mime="application/zip"
    )
    
    st.success(f"已生成包含 {len(st.session_state.processed_documents)} 个文件的ZIP包")

def export_merged_file_with_separators(parent_separator, child_separator, include_metadata, export_format):
    """导出合并文件（所有文档合并为一个文件）"""
    
    if not st.session_state.processed_documents:
        st.error("没有可导出的文档")
        return
    
    from datetime import datetime
    
    all_content_parts = []
    
    for doc in st.session_state.processed_documents:
        chunks = doc.get('chunks', [])
        doc_content = generate_custom_separator_content(chunks, parent_separator, child_separator, include_metadata)
        
        # 添加文档标识
        doc_header = f"=== {doc.get('filename', '未知文档')} ==="
        all_content_parts.append(f"{doc_header}\n{doc_content}")
    
    # 使用双父段分隔符分隔不同文档
    merged_content = f"\n{parent_separator}{parent_separator}\n".join(all_content_parts)
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"merged_custom_separators_{timestamp}.{export_format}"
    
    st.download_button(
        label=f"📥 下载合并文件 ({filename})",
        data=merged_content,
        file_name=filename,
        mime="text/plain" if export_format == "txt" else "text/markdown"
    )
    
    total_chunks = sum(len(doc.get('chunks', [])) for doc in st.session_state.processed_documents)
    st.success(f"已生成合并文件，包含 {len(st.session_state.processed_documents)} 个文档，共 {total_chunks} 个切片")